package net.zigin.nhi.waste.view.collect;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Picture;
import android.os.Bundle;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gyf.immersionbar.ImmersionBar;

import net.zigin.nhi.waste.R;
import net.zigin.nhi.waste.constants.Constants;
import net.zigin.nhi.waste.net.ApiCall;
import net.zigin.nhi.waste.net.BaseResponse;
import net.zigin.nhi.waste.net.HttpRetrofitClient;
import net.zigin.nhi.waste.net.PublicService;
import net.zigin.nhi.waste.utils.BitmapUtils;
import net.zigin.nhi.waste.utils.CommonUtils;

import org.json.JSONException;

import java.util.HashSet;
import java.util.Set;

import Printer.PrintHelper;
import io.paperdb.Paper;
import io.reactivex.Observable;

/**
 * 医废收集打印标签界面
 */
public class CollectPrintActivity extends AppCompatActivity {

    private TextView mHospitalName;
    private ImageView mTypeImg;
    private ImageView mCodeImg;
    private TextView mNumber;
    private TextView mOrigin;
    private TextView mTypeTv;
    private TextView mWeight;
    private TextView mHandover;
    private TextView mTime;
    private Button mPrint;
    private WebView mWebView;

    private String hospitalName;
    private Set<String> wasteQRCodes = new HashSet<>();
    private PrintHelper printHelper;
    private String qrCode;

    org.json.JSONObject printObject;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_collect_print);

        initView();
        printHelper = new PrintHelper();
        printHelper.Open(CollectPrintActivity.this);
    }

    private void initView() {
        ImmersionBar.with(this).init();
        mHospitalName = findViewById(R.id.hospitalName);
        mTypeImg = findViewById(R.id.type_img);
        mCodeImg = findViewById(R.id.code_img);
        mNumber = findViewById(R.id.number);
        mOrigin = findViewById(R.id.origin);
        mTypeTv = findViewById(R.id.type_tv);
        mWeight = findViewById(R.id.weight);
        mHandover = findViewById(R.id.handover);
        mTime = findViewById(R.id.time);
        mPrint = findViewById(R.id.print);
        mWebView = findViewById(R.id.web_view);
    }

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onResume() {
        super.onResume();
        initData();

        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.addJavascriptInterface(new PrintObject(), "connect");
        mWebView.getSettings().setSupportZoom(true);
        mWebView.getSettings().setBuiltInZoomControls(true);
        mWebView.getSettings().setDisplayZoomControls(false);
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.setWebChromeClient(new WebChromeClient());
        mWebView.loadUrl("file:///android_asset/collectPrint.html");

    }

    private void initData() {
        String id = Paper.book().read(Constants.COLLECTID);
        hospitalName = Paper.book().read(Constants.HOSPITAL_NAME);
        if (id != null) {
            Observable<BaseResponse<String>> observable = HttpRetrofitClient.getInstance().create(PublicService.class)
                    .generateQrCode(Paper.book().read(Constants.TOKEN).toString(), id);
            HttpRetrofitClient.execute(observable, new ApiCall<String>() {
                @Override
                protected void success(String data) {
                    Log.i("下载二维码", data);
                    qrCode = data;
                    wasteQRCodes.add(data);
                    Paper.book().write(Constants.WASTE_QRCODES, wasteQRCodes);
                    Bitmap bitmap = BitmapUtils.createQRImage(data, 500, 500);
                    mCodeImg.setImageBitmap(bitmap);

                    Observable<BaseResponse<String>> observable1 = HttpRetrofitClient.getInstance().create(PublicService.class)
                            .getById(Paper.book().read(Constants.TOKEN).toString(), id);
                    HttpRetrofitClient.execute(observable1, new ApiCall<String>() {
                        @Override
                        protected void success(String data) {
                            Log.i("查询医废详情", data);
                            if (data != null) {
                                JSONObject object = JSON.parseObject(data);
                                mNumber.setText(object.getString("code"));
                                mOrigin.setText(object.getString("hospitalDepartName"));
                                mTypeTv.setText(object.getString("wasteClassifyName"));
                                mWeight.setText(object.getString("weight"));
                                mHandover.setText(object.getString("handUserStaffName"));
                                mTime.setText(object.getString("createTime"));
                                if (hospitalName != null) {
                                    mHospitalName.setText(hospitalName);
                                }

                                printObject = new org.json.JSONObject();
                                try {
                                    printObject.put("hospitalName", mHospitalName.getText().toString());
                                    printObject.put("num", mNumber.getText().toString());
                                    printObject.put("departName", mOrigin.getText().toString());
                                    printObject.put("type", mTypeTv.getText().toString());
                                    printObject.put("weight", mWeight.getText().toString());
                                    printObject.put("handover", mHandover.getText().toString());
                                    printObject.put("time", mTime.getText().toString());
                                    printObject.put("qrCode", qrCode);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                                Log.i("printObject", printObject.toString());
                                String call = "javascript:getCollectDetail(" + printObject.toString() + ")";
                                mWebView.loadUrl(call);
                            }
                        }
                    });
                }
            });
        }

        mPrint.setOnClickListener(v -> {
            if(CommonUtils.isFastClick()){
                return;
            }
            mWebView.loadUrl("javascript:scanprint()");
            finish();
        });
    }

    class PrintObject {
        @JavascriptInterface
        public void print(final int x, final int y, final int width, final int height) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Picture pic = mWebView.capturePicture();
                        int nw = pic.getWidth();
                        int nh = pic.getHeight();
                        Bitmap bitmap = Bitmap.createBitmap(nw, nh, Bitmap.Config.ARGB_4444);
                        Canvas can = new Canvas(bitmap);
                        pic.draw(can);

                        int newWidth = nw;
                        int newHeight = nh;
                        if (nw > 400) {
                            float rate = 380 * 1.0f / nw * 1.0f;
                            newWidth = 380;
                            newHeight = (int) (nh * rate);
                        }
                        bitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
                        Bitmap newBitmap = Bitmap.createBitmap(bitmap, x, y, width, height);
                        printHelper.PrintBitmap(newBitmap);
                    } catch (Exception | Error e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        @JavascriptInterface
        public void doFeed() {
            printHelper.Step((byte) 0x5f);
        }
    }
}